import { getAreaInfo, getAreaInfoById, getAreaTree, getAreaTreeByXid, s_getSelectData, test_jwt, updateAreaInfo} from "@/services/basis";
import { useModel, useRequest } from "@umijs/max";
import { Card ,Tree,Row,Col,Space,Input,Button,Radio, Form, DatePicker, message} from "antd";
import dayjs from "dayjs";
import { useRef, useState } from "react";
import locale from "antd/es/date-picker/locale/zh_CN";
import moment from "moment";
import { Access,useAccess } from "@umijs/max";
import { ProCard, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText } from "@ant-design/pro-components";
import { currentUser } from "@/services/ant-design-pro/api";

const App:React.FC=()=>{
   const { initialState, setInitialState } = useModel('@@initialState');
   // operater_id:initialState?.currentUser?.userid
   const [tdata,setTdata]=useState();//树数据源,用state上的是新增或编辑项目时，自动更新 树
   const [tnode,setTnode]=useState<{key:any,title:any}>();//左侧区域树选中项的code,可按此带出右侧明细信息
   const [etype,setEtype]=useState(0);//用于判断是新增还是修改。
   const [expandKeys,setExpandKeys]=useState([]);
   
   //带参数时，要加上前面的小括号调用
    useRequest(()=>getAreaTreeByXid({x_id:1}),{
      onSuccess:(data:any)=>{
         setTdata(data.ctree);
         setExpandKeys(data.keys);
      }
    });   

   const mform_ref=useRef<ProFormInstance>();
   const access=useAccess();
   // alert(JSON.stringify(access));

   //按code获取区域 定义信息
   async function getInfo(node:{key:any,title:any}){
       setEtype(0);//
       // alert(JSON.stringify(node));
        const info=await getAreaInfoById({id:node.key});
         //alert(JSON.stringify(info));
        const fdata={...info.data,
                  operate_time:moment(moment(info.data.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
                   };
  
        mform_ref.current?.setFieldsValue({
               code:fdata.code,name:fdata.name,higher_name:fdata.higher_name,
               operate_time:fdata.operate_time,
               status:fdata.status,operater_id:fdata.operater_id,
               isend:fdata.isend,
               });   
      setTnode(node);//保存当前的id，在新增时使用
   }


    //新增按钮，将表单清空
    function addArea(){
       
      if(tnode?.key===0||mform_ref.current?.getFieldValue('name')===undefined)
         message.warning('请先选择要添加的目标组织。');
      else{
         const higher_name=mform_ref.current?.getFieldValue('name');
         mform_ref.current?.resetFields();
         mform_ref.current?.setFieldsValue({higher_name:higher_name,operate_time:moment().toDate(),operater_id:1,isend:0});
         setEtype(1);
      }
    }

//保存新增或修改的内容:etype:1新增，0修改
 async function saveArea(){
//先取出表单值，再调用接口updateAreaInfo( ttype,tdata)
//原higher_code，要如何取？
    const fdata=mform_ref.current?.getFieldsValue();
    const fdata2={...fdata,higher_id:tnode?.key, 
                   higher_code:tnode?.title.substring(0,tnode?.title.indexOf(' ')), 
                   id:tnode?.key, 
                  operate_time:moment(moment(fdata.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss')};
   //  alert(JSON.stringify(fdata2));
   //mform_ref.current?.submit();
   const r=await updateAreaInfo({x_id:1,operater_id:1,ttype:etype,tdata:fdata2});
    if(r.success){
      message.success('数据保存成功 ！');
      //alert(JSON.stringify(r.data ));
      setTdata(r.data);
      }
    else
      message.error('数据保存失败，请检查。');

 }

//  alert(initialState?.currentUser?.hasRoute);
//=================================================================================
   return(
      
        <ProForm name='mform' formRef={mform_ref}   layout="horizontal" labelAlign="left" labelCol={{offset:0,span:3}}
           submitter={false}    onFinish={()=>saveArea()}
           initialValues={{operater_id:initialState?.currentUser?.userid}}
        >
       {/* {JSON.stringify(initialState?.currentUser)} */}

         <Row gutter={8}>
            <Col span={6}>
               <ProCard style={{height:'75vh'}} title='区域'>
                  <Tree treeData={tdata} expandedKeys={expandKeys} 
                       onExpand={(ekeys:any)=>setExpandKeys(ekeys)}
                       blockNode={true} onClick={(e,node)=>getInfo({key:node.key,title:node.title})}
                 />
               </ProCard>
            </Col>
            <Col span={18}>
               <ProCard style={{height:'75vh',overflow:'auto'}} title='区域定义' bodyStyle={{marginLeft:80}}
               extra={<Space size='large'>
                 {/* <Access accessible={access.operateFilter('area_add')}  >  */}
                       <Button onClick={()=>addArea()}>新增</Button>
                  {/* </Access> */}
                {/* <Access accessible={access.operateFilter('area_save')} >  */}
                       <Button onClick={()=>mform_ref.current?.submit()}>保存</Button>
                       <Button onClick={()=>test_jwt({})}>测试jwt</Button>
                  {/* </Access> */}
                  </Space>}
                 /* <Button onClick={()=>saveArea()}>保存内容</Button></Space>} */
               >
                {/* {JSON.stringify(tnode)} */}
               <ProFormText name='code' label='区域编号' width={300}  
                    rules={[{required:true,message:'必须录入编辑'}]} />
               <ProFormText name='name' label='区域名称' 
                    rules={[{required:true,message:'必须录入名称'}]} width={300}/>
               {/* <ProFormRadio.Group name='isend' label='小程序'
                   options={[{label:'不展示',value:0},{label:'展示',value:1}]}
                    />  */}
               <ProFormText name='higher_name' label='上级名称' width={300} disabled/>
               <ProFormDatePicker name='operate_time' label='创建日期'width={300} disabled/>
               <ProFormRadio.Group name='status' label='状态' width={300} initialValue={1}
                 options={[{value:1,label:'启用'},{value:2,label:'冻结'},{value:3,label:'删除'}]}
                 />
               <ProFormSelect name='operater_id' label='操作人' width={300}
                    showSearch
                     request={async ()=>{
                        const x=await s_getSelectData({x_id:1,source:'base_person'});
                        return x.data;}}
                 />
          
               </ProCard>
            </Col>
         </Row>
      </ProForm> 
      
   );
}

export default App;